const fs = require("fs");
const { JSDOM } = require("jsdom");
const url = require("url");
const axios = require("axios");
// segment 中文分词

function getUrl(sUrl, success) {
  let urlObj = url.parse(sUrl);
  let http = "";
  if (urlObj.protocol === "http") {
    http = require("http");
  } else {
    http = require("https");
  }

  let req = http.request(
    {
      hostname: urlObj.hostname,
      path: urlObj.path,
    },
    (res) => {
      let arr = [];
      let str = "";
      res.on("data", (buffer) => {
        arr.push(buffer);
        str += buffer;
      });
      res.on("end", () => {
        //   文件
        let result = Buffer.concat(arr);
        success && success(result, str);
      });
    }
  );
  req.on("error", (err) => {
    console.log("出错了");
  });
  req.end();
}

function getUrl2(url, callFn) {
  axios({
    method: "get",
    url,
    // responseType: "stream",
    params: {},
  }).then((res) => {
    if (res.status === 200) {
      console.log(res.data);
      // callFn(res.data);
    }
  });
}

getUrl2("http://localhost:8000/api/blog/detail?id=2", (data, str) => {
  //   fs.writeFile("download.html", data, { encoding: "utf-8" }, () => {
  //     console.log("写入成功了");
  //   });
  //   const DOM = new JSDOM(data);
  //   console.log(str);
  const DOM = new JSDOM(str);
  let doc = DOM.window.document;
  let ele = doc.querySelector(".p-name");
  console.log(ele.textContent);
});
